import streamlit as st

st.title ("this is the app title")
st.header("this is the markdown")
st.subheader("this is the subheader")
st.write("Hello ,let's learn how to build a streamlit app together")

st.markdown("- this is the makdown")
st.caption("this is the caption")
st.code("x=2021")
st.latex(r''' a+a r^1+a r^2+a r^3 ''')

st.checkbox('yes')
st.button('Click')
st.radio('Pick your gender',['Male','Female'])
st.selectbox('Pick your gender',['Male','Female'])
st.multiselect('choose a planet',['Jupiter', 'Mars', 'neptune'])
st.select_slider('Pick a mark', ['Bad', 'Good', 'Excellent'])
st.slider('Pick a number', 0,50)

st.number_input('Pick a number', 0,10)
st.text_input('Email address')
st.date_input('Travelling date')
st.time_input('School time')
st.text_area('Description')
st.file_uploader('Upload a photo')
st.color_picker('Choose your favorite color')

st.balloons()
st.progress(10)
import time
with st.spinner('Wait for it...'):    
	time.sleep(2)

st.success("You did it !")
st.error("Error")
st.warning("Warning")
st.info("It's easy to build a streamlit app")
st.exception(RuntimeError("RuntimeError exception"))


import matplotlib.pyplot as plt
import numpy as np
rand=np.random.normal(1, 2, size=20)
fig, ax = plt.subplots()
ax.hist(rand, bins=15)
st.pyplot(fig)

import pandas as pd
import numpy as np
df= pd.DataFrame(np.random.randn(10, 2),columns=['x', 'y'])
st.line_chart(df)
df= pd.DataFrame(np.random.randn(10, 2),columns=['x', 'y'])
st.bar_chart(df)

# 创建一个示例数据集
data = {
    'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'],
    'Sales': [100, 150, 200, 120]
}
df = pd.DataFrame(data)
# 展示折线图
st.title('销售趋势')
st.line_chart(df['Sales'])

st.write("这是一个使用 <span style='color: blue;'>HTML标签</span> 的示例。",
         unsafe_allow_html=True)

st.write("<div></div>", unsafe_allow_html=True)


# 创建示例数据集
data = {
    'Product': ['Product A', 'Product B', 'Product C'],
    'Sales': [200, 300, 150]
}
df = pd.DataFrame(data)
# 创建下拉菜单并根据选择筛选数据
selected_product = st.selectbox("选择产品：", df['Product'])
filtered_df = df[df['Product'] == selected_product]
# 展示筛选后的数据
st.write(f"你选择的产品的销售情况：{selected_product}")
st.table(filtered_df)


# 创建示例数据集
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [25, 30, 28, 22]
}
df = pd.DataFrame(data)
# 创建滑动条和多选框来过滤数据
min_age = st.slider("最小年龄：", min_value=0, max_value=100, value=0)
max_age = st.slider("最大年龄：", min_value=0, max_value=100, value=100)
selected_ages = st.multiselect("选择年龄：", df['Age'].unique())
# 根据过滤条件筛选数据
filtered_df = df[(df['Age'] >= min_age) & (df['Age'] <= max_age) & (df['Age'].isin(selected_ages))]
# 展示筛选后的数据
st.write("你选择的年龄范围和年龄筛选：")
st.table(filtered_df)


# 初始化计数器
counter = st.number_input("请输入计数器的初始值：", value=0)
# 实时更新计数器
if st.button("增加"):
    counter += 1
    st.write(f"当前计数器值：{counter}")

st.markdown("""
<style>
body {
    font-family: 'Arial', sans-serif;
    color: #333;
}
</style>
""", unsafe_allow_html=True)




st.write('*'*10)
st.write('+'*15)
st.write('='*10)

var_name = "my_variable"
value = 10
# 创建动态变量并赋值
exec(f'{var_name} = {value}')
print(my_variable)  # 输出结果为 10
st.write('*'*10)


import pandas as pd
import os

# 获取文件名
file_path = 'your_file_path_here'
filename = os.path.basename(file_path)

# 动态创建DataFrame对象
exec(f'df_{filename} = pd.read_csv(file_path)')

# 现在你可以直接使用df_filename来访问这个DataFrame对象
print(df_filename)
st.write('*'*10)



# 添加一个文本输入框，用户可以在其中输入 Python 代码
code = st.text_area('请在此输入 Python 代码')
# 如果用户输入了代码并点击了运行按钮，那么就运行这段代码
if st.button('运行'):
    try:
        exec(code)
    except Exception as e:
        st.write(f'运行出错: {e}')
st.write('*'*10)


from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
# 在应用的其他部分定义变量 x
x = 10

# # 添加一个代码编辑器，并使用 Pygments 对代码进行高亮显示
# code = st.code_editor('代码编辑器', language='python')
# if st.button('运行'):
#     try:
#         # 在代码块中访问和修改变量 x
#         x = int(code)
#         st.write(f'变量 x 的新值为: {x}')
#     except Exception as e:
#         st.write(f'运行出错: {e}')

file_path = st.file_uploader('请选择一个代码文件')
if file_path:
    with open(file_path, 'r') as file:
        code = file.read()

lexer = PythonLexer()
formatter = HtmlFormatter()
highlighted_code = highlight(code, lexer, formatter)
st.write(highlighted_code, unsafe_allow_html=True)
st.write(highlighted_code, unsafe_allow_html=False)


